/**
 * 定义路由： Router.[method](path, (request, response) => { })
 *    Router: 路由实例
 *    app.method(path, (request, response) => { })
 */
// 使用 multer 处理文件上传
const multer = require("multer");
const { v4: uuid } = require("uuid");
const path = require("path");

// jwt
const { getPayloadByToken } = require("../jwt");
// 配置上传文件的存储位置和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/avatars");
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, uuid() + ext);
  },
});

const useAuthorization = async (req, res, next) => {
  // console.log(4);
  // 从请求头部获得 token
  const { authorization } = req.headers;
  // console.log(req.headers);

  const payload = getPayloadByToken(authorization);
  // 获取用户id
  const userId = payload?.userId || req.session?.userId;
  // console.log(3);
  // console.log(payload?.userId,payload,authorization);
  // 通过 session.userId 判断用户是否登录
  if (!userId) {
    return res.status(401).send({ success: false, message: "用户尚未登录!" });
    // console.log(2);
  }
  // 为以后获取用户信息方便，将用户信息保存在 req.user 上。
  req.user = await db.findOne`select * from user where id = ${userId}`;
  // console.log(1);
  // console.log(req.user, userId)
  next();
};

const upload = multer({ storage });

const { db } = require("../database");

const { validate, validators } = require("../validate");

// 导入加密函数
const { makePassword, checkPassword } = require("../utils");
// jwt
const { sign } = require("../jwt");
const multiAvatar = require("@multiavatar/multiavatar");

const router = require("express").Router();
router
  /**
   * 用户登录
   */
  .post(
    "/login",
    validate(validators.username, validators.password),
    async (req, res) => {
      const { username, password } = req.body;
      // console.log(username);
      // console.log(req.body)
      // 根据用户名查询用户信息
      const user = await db.findOne("select * from user where username = ?", [
        username,
      ]);
      // 判断密码是否输入正确
      const person = await db.findOne("select * from person where id =?", [
        user.person,
      ]);
      if (user && checkPassword(password, user.password)) {
        // 在会话（session）中保存用户信息
        req.session.userId = user.id;
        // 签发 token 给客户端代码
        const token = sign({ userId: user.id });
        res.header("Authorization", token);
        // console.log(token);
        return res.send({
          code: 200,
          message: "成功",
          result: {
            token,
            user: {
              id: person.id,
              name: person.name,
              sex: person.sex,
              address: person.address,
              duty: person.duty,
              phone: person.phone,
              description: person.description,
              org: person.org,
              avatar: 'http://localhost:3333/avatars/' + user.avatar,
            },
          },
          type: "success",
        });
      }
      res.send({ success: false, message: "用户名或密码错误！" });
    }
  )
  .get("/multi-avatar/:id.svg", async (req, res) => {
    res.type("Image/svg+xml");
    res.send(multiAvatar(req.params.id));
  });

const registerRouter = (app) => app.use("/", router);
module.exports = { registerRouter, useAuthorization };
